Fixed some doxygen warnings
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @author <brion@pobox.com>
19 * @author <mail@tgries.de>
20 * @author Tim Starling
21 *
22 */
23
24
25 /**
26 * Stores a single person's name and email address.
27 * These are passed in via the constructor, and will be returned in SMTP
28 * header format when requested.
29 */
30 class MailAddress {
31 /**
32 * @param $address Mixed: string with an email address, or a User object
33 * @param $name String: human-readable name if a string address is given
34 * @param $realName String: human-readable real name if a string address is given
35 */
36 function __construct( $address, $name = null, $realName = null ) {
37 if( is_object( $address ) && $address instanceof User ) {
38 $this->address = $address->getEmail();
39 $this->name = $address->getName();
40 $this->realName = $address->getRealName();
41 } else {
42 $this->address = strval( $address );
43 $this->name = strval( $name );
44 $this->realName = strval( $realName );
45 }
46 }
47
48 /**
49 * Return formatted and quoted address to insert into SMTP headers
50 * @return string
51 */
52 function toString() {
53 # PHP's mail() implementation under Windows is somewhat shite, and
54 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
55 # so don't bother generating them
56 if( $this->name != '' && !wfIsWindows() ) {
57 global $wgEnotifUseRealName;
58 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
59 $quoted = wfQuotedPrintable( $name );
60 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
61 $quoted = '"' . $quoted . '"';
62 }
63 return "$quoted <{$this->address}>";
64 } else {
65 return $this->address;
66 }
67 }
68
69 function __toString() {
70 return $this->toString();
71 }
72 }
73
74
75 /**
76 * Collection of static functions for sending mail
77 */
78 class UserMailer {
79 static $mErrorString;
80
81 /**
82 * Send mail using a PEAR mailer
83 */
84 protected static function sendWithPear($mailer, $dest, $headers, $body)
85 {
86 $mailResult = $mailer->send($dest, $headers, $body);
87
88 # Based on the result return an error string,
89 if( PEAR::isError( $mailResult ) ) {
90 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
91 return new WikiError( $mailResult->getMessage() );
92 } else {
93 return true;
94 }
95 }
96
97 /**
98 * This function will perform a direct (authenticated) login to
99 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
100 * array of parameters. It requires PEAR:Mail to do that.
101 * Otherwise it just uses the standard PHP 'mail' function.
102 *
103 * @param $to MailAddress: recipient's email (or an array of them)
104 * @param $from MailAddress: sender's email
105 * @param $subject String: email's subject.
106 * @param $body String: email's text.
107 * @param $replyto MailAddress: optional reply-to email (default: null).
108 * @param $contentType String: optional custom Content-Type
109 * @return mixed True on success, a WikiError object on failure.
110 */
111 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
112 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
113 global $wgEnotifMaxRecips;
114
115 if ( is_array( $to ) ) {
116 // This wouldn't be necessary if implode() worked on arrays of
117 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
118 foreach( $to as $t ) {
119 $emails .= $t->toString() . ",";
120 }
121 $emails = rtrim( $emails, ',' );
122 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
123 } else {
124 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
125 }
126
127 if (is_array( $wgSMTP )) {
128 require_once( 'Mail.php' );
129
130 $msgid = str_replace(" ", "_", microtime());
131 if (function_exists('posix_getpid'))
132 $msgid .= '.' . posix_getpid();
133
134 if (is_array($to)) {
135 $dest = array();
136 foreach ($to as $u)
137 $dest[] = $u->address;
138 } else
139 $dest = $to->address;
140
141 $headers['From'] = $from->toString();
142
143 if ($wgEnotifImpersonal) {
144 $headers['To'] = 'undisclosed-recipients:;';
145 }
146 else {
147 $headers['To'] = implode( ", ", (array )$dest );
148 }
149
150 if ( $replyto ) {
151 $headers['Reply-To'] = $replyto->toString();
152 }
153 $headers['Subject'] = wfQuotedPrintable( $subject );
154 $headers['Date'] = date( 'r' );
155 $headers['MIME-Version'] = '1.0';
156 $headers['Content-type'] = (is_null($contentType) ?
157 'text/plain; charset='.$wgOutputEncoding : $contentType);
158 $headers['Content-transfer-encoding'] = '8bit';
159 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
160 $headers['X-Mailer'] = 'MediaWiki mailer';
161
162 // Create the mail object using the Mail::factory method
163 $mail_object =& Mail::factory('smtp', $wgSMTP);
164 if( PEAR::isError( $mail_object ) ) {
165 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
166 return new WikiError( $mail_object->getMessage() );
167 }
168
169 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
170 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
171 foreach ($chunks as $chunk) {
172 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
173 if( WikiError::isError( $e ) )
174 return $e;
175 }
176 } else {
177 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
178 # (fifth parameter of the PHP mail function, see some lines below)
179
180 # Line endings need to be different on Unix and Windows due to
181 # the bug described at http://trac.wordpress.org/ticket/2603
182 if ( wfIsWindows() ) {
183 $body = str_replace( "\n", "\r\n", $body );
184 $endl = "\r\n";
185 } else {
186 $endl = "\n";
187 }
188 $ctype = (is_null($contentType) ?
189 'text/plain; charset='.$wgOutputEncoding : $contentType);
190 $headers =
191 "MIME-Version: 1.0$endl" .
192 "Content-type: $ctype$endl" .
193 "Content-Transfer-Encoding: 8bit$endl" .
194 "X-Mailer: MediaWiki mailer$endl".
195 'From: ' . $from->toString();
196 if ($replyto) {
197 $headers .= "{$endl}Reply-To: " . $replyto->toString();
198 }
199
200 wfDebug( "Sending mail via internal mail() function\n" );
201
202 self::$mErrorString = '';
203 $html_errors = ini_get( 'html_errors' );
204 ini_set( 'html_errors', '0' );
205 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
206
207 if (is_array($to)) {
208 foreach ($to as $recip) {
209 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
210 }
211 } else {
212 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
213 }
214
215 restore_error_handler();
216 ini_set( 'html_errors', $html_errors );
217
218 if ( self::$mErrorString ) {
219 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
220 return new WikiError( self::$mErrorString );
221 } elseif (! $sent ) {
222 //mail function only tells if there's an error
223 wfDebug( "Error sending mail\n" );
224 return new WikiError( 'mail() failed' );
225 } else {
226 return true;
227 }
228 }
229 }
230
231 /**
232 * Set the mail error message in self::$mErrorString
233 *
234 * @param $code Integer: error number
235 * @param $string String: error message
236 */
237 static function errorHandler( $code, $string ) {
238 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
239 }
240
241 /**
242 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
243 */
244 static function rfc822Phrase( $phrase ) {
245 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
246 return '"' . $phrase . '"';
247 }
248 }
249
250 /**
251 * This module processes the email notifications when the current page is
252 * changed. It looks up the table watchlist to find out which users are watching
253 * that page.
254 *
255 * The current implementation sends independent emails to each watching user for
256 * the following reason:
257 *
258 * - Each watching user will be notified about the page edit time expressed in
259 * his/her local time (UTC is shown additionally). To achieve this, we need to
260 * find the individual timeoffset of each watching user from the preferences..
261 *
262 * Suggested improvement to slack down the number of sent emails: We could think
263 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
264 * same timeoffset in their preferences.
265 *
266 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
267 *
268 *
269 */
270 class EmailNotification {
271 protected $to, $subject, $body, $replyto, $from;
272 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
273 protected $mailTargets = array();
274
275 /**
276 * Send emails corresponding to the user $editor editing the page $title.
277 * Also updates wl_notificationtimestamp.
278 *
279 * May be deferred via the job queue.
280 *
281 * @param $editor User object
282 * @param $title Title object
283 * @param $timestamp
284 * @param $summary
285 * @param $minorEdit
286 * @param $oldid (default: false)
287 */
288 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
289 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
290
291 if ($title->getNamespace() < 0)
292 return;
293
294 // Build a list of users to notfiy
295 $watchers = array();
296 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
297 $dbw = wfGetDB( DB_MASTER );
298 $res = $dbw->select( array( 'watchlist' ),
299 array( 'wl_user' ),
300 array(
301 'wl_title' => $title->getDBkey(),
302 'wl_namespace' => $title->getNamespace(),
303 'wl_user != ' . intval( $editor->getID() ),
304 'wl_notificationtimestamp IS NULL',
305 ), __METHOD__
306 );
307 while ($row = $dbw->fetchObject( $res ) ) {
308 $watchers[] = intval( $row->wl_user );
309 }
310 if ($watchers) {
311 // Update wl_notificationtimestamp for all watching users except
312 // the editor
313 $dbw->begin();
314 $dbw->update( 'watchlist',
315 array( /* SET */
316 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
317 ), array( /* WHERE */
318 'wl_title' => $title->getDBkey(),
319 'wl_namespace' => $title->getNamespace(),
320 'wl_user' => $watchers
321 ), __METHOD__
322 );
323 $dbw->commit();
324 }
325 }
326
327 if ($wgEnotifUseJobQ) {
328 $params = array(
329 "editor" => $editor->getName(),
330 "editorID" => $editor->getID(),
331 "timestamp" => $timestamp,
332 "summary" => $summary,
333 "minorEdit" => $minorEdit,
334 "oldid" => $oldid,
335 "watchers" => $watchers);
336 $job = new EnotifNotifyJob( $title, $params );
337 $job->insert();
338 } else {
339 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
340 }
341
342 }
343
344 /*
345 * Immediate version of notifyOnPageChange().
346 *
347 * Send emails corresponding to the user $editor editing the page $title.
348 * Also updates wl_notificationtimestamp.
349 *
350 * @param $editor User object
351 * @param $title Title object
352 * @param $timestamp string Edit timestamp
353 * @param $summary string Edit summary
354 * @param $minorEdit bool
355 * @param $oldid int Revision ID
356 * @param $watchers array of user IDs
357 */
358 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
359 # we use $wgPasswordSender as sender's address
360 global $wgEnotifWatchlist;
361 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
362 global $wgEnotifImpersonal;
363
364 wfProfileIn( __METHOD__ );
365
366 # The following code is only run, if several conditions are met:
367 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
368 # 2. minor edits (changes) are only regarded if the global flag indicates so
369
370 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
371 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
372 $enotifwatchlistpage = $wgEnotifWatchlist;
373
374 $this->title = $title;
375 $this->timestamp = $timestamp;
376 $this->summary = $summary;
377 $this->minorEdit = $minorEdit;
378 $this->oldid = $oldid;
379 $this->editor = $editor;
380 $this->composed_common = false;
381
382 $userTalkId = false;
383
384 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
385 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
386 $targetUser = User::newFromName( $title->getText() );
387 if ( !$targetUser || $targetUser->isAnon() ) {
388 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
389 } elseif ( $targetUser->getId() == $editor->getId() ) {
390 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
391 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
392 if( $targetUser->isEmailConfirmed() ) {
393 wfDebug( __METHOD__.": sending talk page update notification\n" );
394 $this->compose( $targetUser );
395 $userTalkId = $targetUser->getId();
396 } else {
397 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
398 }
399 } else {
400 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
401 }
402 }
403
404 if ( $wgEnotifWatchlist ) {
405 // Send updates to watchers other than the current editor
406 $userArray = UserArray::newFromIDs( $watchers );
407 foreach ( $userArray as $watchingUser ) {
408 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
409 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
410 $watchingUser->isEmailConfirmed() &&
411 $watchingUser->getID() != $userTalkId )
412 {
413 $this->compose( $watchingUser );
414 }
415 }
416 }
417 }
418
419 global $wgUsersNotifiedOnAllChanges;
420 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
421 $user = User::newFromName( $name );
422 $this->compose( $user );
423 }
424
425 $this->sendMails();
426 wfProfileOut( __METHOD__ );
427 }
428
429 /**
430 * @private
431 */
432 function composeCommonMailtext() {
433 global $wgPasswordSender, $wgNoReplyAddress;
434 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
435 global $wgEnotifImpersonal, $wgEnotifUseRealName;
436
437 $this->composed_common = true;
438
439 $summary = ($this->summary == '') ? ' - ' : $this->summary;
440 $medit = ($this->minorEdit) ? wfMsgForContent( 'minoredit' ) : '';
441
442 # You as the WikiAdmin and Sysops can make use of plenty of
443 # named variables when composing your notification emails while
444 # simply editing the Meta pages
445
446 $subject = wfMsgForContent( 'enotif_subject' );
447 $body = wfMsgForContent( 'enotif_body' );
448 $from = ''; /* fail safe */
449 $replyto = ''; /* fail safe */
450 $keys = array();
451
452 if( $this->oldid ) {
453 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
454 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
455 $keys['$OLDID'] = $this->oldid;
456 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
457 } else {
458 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
459 # clear $OLDID placeholder in the message template
460 $keys['$OLDID'] = '';
461 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
462 }
463
464 if ($wgEnotifImpersonal && $this->oldid)
465 /*
466 * For impersonal mail, show a diff link to the last
467 * revision.
468 */
469 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
470 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
471
472 $body = strtr( $body, $keys );
473 $pagetitle = $this->title->getPrefixedText();
474 $keys['$PAGETITLE'] = $pagetitle;
475 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
476
477 $keys['$PAGEMINOREDIT'] = $medit;
478 $keys['$PAGESUMMARY'] = $summary;
479 $keys['$UNWATCHURL'] = $this->title->getFullUrl( 'action=unwatch' );
480
481 $subject = strtr( $subject, $keys );
482
483 # Reveal the page editor's address as REPLY-TO address only if
484 # the user has not opted-out and the option is enabled at the
485 # global configuration level.
486 $editor = $this->editor;
487 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
488 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
489 $editorAddress = new MailAddress( $editor );
490 if( $wgEnotifRevealEditorAddress
491 && ( $editor->getEmail() != '' )
492 && $editor->getOption( 'enotifrevealaddr' ) ) {
493 if( $wgEnotifFromEditor ) {
494 $from = $editorAddress;
495 } else {
496 $from = $adminAddress;
497 $replyto = $editorAddress;
498 }
499 } else {
500 $from = $adminAddress;
501 $replyto = new MailAddress( $wgNoReplyAddress );
502 }
503
504 if( $editor->isIP( $name ) ) {
505 #real anon (user:xxx.xxx.xxx.xxx)
506 $utext = wfMsgForContent('enotif_anon_editor', $name);
507 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
508 $keys['$PAGEEDITOR'] = $utext;
509 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
510 } else {
511 $subject = str_replace('$PAGEEDITOR', $name, $subject);
512 $keys['$PAGEEDITOR'] = $name;
513 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
514 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
515 }
516 $userPage = $editor->getUserPage();
517 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
518 $body = strtr( $body, $keys );
519 $body = wordwrap( $body, 72 );
520
521 # now save this as the constant user-independent part of the message
522 $this->from = $from;
523 $this->replyto = $replyto;
524 $this->subject = $subject;
525 $this->body = $body;
526 }
527
528 /**
529 * Compose a mail to a given user and either queue it for sending, or send it now,
530 * depending on settings.
531 *
532 * Call sendMails() to send any mails that were queued.
533 */
534 function compose( $user ) {
535 global $wgEnotifImpersonal;
536
537 if ( !$this->composed_common )
538 $this->composeCommonMailtext();
539
540 if ( $wgEnotifImpersonal ) {
541 $this->mailTargets[] = new MailAddress( $user );
542 } else {
543 $this->sendPersonalised( $user );
544 }
545 }
546
547 /**
548 * Send any queued mails
549 */
550 function sendMails() {
551 global $wgEnotifImpersonal;
552 if ( $wgEnotifImpersonal ) {
553 $this->sendImpersonal( $this->mailTargets );
554 }
555 }
556
557 /**
558 * Does the per-user customizations to a notification e-mail (name,
559 * timestamp in proper timezone, etc) and sends it out.
560 * Returns true if the mail was sent successfully.
561 *
562 * @param $watchingUser User object
563 * @return Boolean
564 * @private
565 */
566 function sendPersonalised( $watchingUser ) {
567 global $wgContLang, $wgEnotifUseRealName;
568 // From the PHP manual:
569 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
570 // The mail command will not parse this properly while talking with the MTA.
571 $to = new MailAddress( $watchingUser );
572 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
573 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
574
575 $timecorrection = $watchingUser->getOption( 'timecorrection' );
576
577 # $PAGEEDITDATE is the time and date of the page change
578 # expressed in terms of individual local time of the notification
579 # recipient, i.e. watching user
580 $body = str_replace(
581 array( '$PAGEEDITDATEANDTIME',
582 '$PAGEEDITDATE',
583 '$PAGEEDITTIME' ),
584 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
585 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
586 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
587 $body);
588
589 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
590 }
591
592 /**
593 * Same as sendPersonalised but does impersonal mail suitable for bulk
594 * mailing. Takes an array of MailAddress objects.
595 */
596 function sendImpersonal( $addresses ) {
597 global $wgContLang;
598
599 if (empty($addresses))
600 return;
601
602 $body = str_replace(
603 array( '$WATCHINGUSERNAME',
604 '$PAGEEDITDATE'),
605 array( wfMsgForContent('enotif_impersonal_salutation'),
606 $wgContLang->timeanddate($this->timestamp, true, false, false)),
607 $this->body);
608
609 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
610 }
611
612 } # end of class EmailNotification
613
614 /**
615 * Backwards compatibility functions
616 */
617 function wfRFC822Phrase( $s ) {
618 return UserMailer::rfc822Phrase( $s );
619 }
620
621 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
622 return UserMailer::send( $to, $from, $subject, $body, $replyto );
623 }